using System;
using Globals;
using UnityEngine;
using Utils;

namespace Actions
{
    public class Mover : MonoBehaviour
    {
        public bool IsMoving => _moveDirection != Vector2.zero;
        
        private bool IsFrozen => _freezeTimer.IsActive;
        
        private Timer _freezeTimer;

        private Rigidbody2D _rigidbody2D;

        private Vector2 _moveDirection;


        private void Awake()
        {
            _rigidbody2D = GetComponent<Rigidbody2D>();
            
            _freezeTimer = new Timer(0f);
        }

        private void Update()
        {
            _freezeTimer.Tick();
        }

        private void FixedUpdate()
        {
            if (IsFrozen) return;
            
            _rigidbody2D.velocity = GlobalEnemyData.Instance.EnemyMoveSpeed * _moveDirection;
        }

        public void Move(Vector2 moveDirection)
        {
            _moveDirection = moveDirection;
        }

        public void StopMoving()
        {
            _moveDirection = Vector2.zero;
        }

        public void Knock(Vector2 direction, float force, float freezeTime)
        {
            _freezeTimer.Reset(freezeTime);
            
            _rigidbody2D.velocity = Vector2.zero;
            _rigidbody2D.AddForce(force * direction, ForceMode2D.Impulse);
        }
        
        private void Health_Died()
        {
            StopMoving();
        }
    }
}